<?php

namespace App\Repository;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Base\Menu;
use App\Models\Role\RoleMenuBind;
use Illuminate\Support\Facades\Log;

/**
 * 中台菜单数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class MenuRepository extends BaseRepository
{
    /**
     * 保存数据
     *
     * @param array $data
     * @param int $menuId
     * @throws
     * @return int|mixed
     */
    public function save(array $data, int $menuId = 0)
    {
        try {
            $query = $menuId ? Menu::find($menuId) : new Menu();
            collect($data)->each(function ($value, $field) use ($query) {
                $query->{$field} = $value;
            });
            return $query->save() ? $query->menu_id : 0;
        } catch (\Exception $exception) {
            Log::error("[系统菜单] 保存失败：{$exception->getMessage()}");
            throw new BusinessException(ResponseCode::SAVE_FAIL);
        }
    }

    /**
     * 获取菜单列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(array $filter = [])
    {
        $qurey = Menu::query()->orderBy('sort_num', 'asc');
        if(isset($filter['is_active'])) {
            $qurey->where('is_active', $filter['is_active']);
        }
        if(!empty($filter['menu_name'])) {
            $qurey->where('menu_name', 'like', '%' . $filter['menu_name'] . '%');
        }
        return $qurey;
    }

    /**
     * 获取用户可用的菜单
     *
     * @param int $userId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getUserMenu(int $userId)
    {
        $roleIds = UserRepository::getInstance()->getById($userId);
        return RoleMenuBind::query()->whereIn('role_id', $roleIds)->get();
    }

    /**
     * 根据父Id获取子菜单
     *
     * @param int $parentId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getByParentId(int $parentId)
    {
        return Menu::query()->where('parent_id', $parentId)->where('is_active', 1)->get();
    }

    /**
     * 根据级数获取菜单
     *
     * @param int $level
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getByLevel(int $level)
    {
        return Menu::query()->where('level', $level)->where('is_active', 1)->get();
    }
}
